<?php
/**
 *
 * @author Quentin Laujac, Charles Hurtevent
 *
 */
require_once ("../enums/enums.php");
require_once ("../bean/data/Article.php");
require_once ("../bean/data/Commande.php");
require_once ("../bean/data/Facture.php");
require_once ("../bean/data/Utilisateur.php");
require_once ("../services/ClientService.php");

// si le formulaire est envoye
if($_POST['submitCommande'] != null) {
	session_start();
	//creation des objets
	$clientService = new ClientService();
	$commande = new Commande();
	$listArticleCommande = new ArrayObject();
	$facture = new Facture();
	$date = new DateTime();
	$dateCommande = $date->format('Y-m-d H:i:s');
	$client = $_SESSION['login'];
	$listLieu = $_SESSION ['listLieu'];


	//recuperation des articles choisi
	foreach ( $_SESSION['listArticle'] as $article ) {
		$article->setQuantiteCommandee($_POST['quantite'.$article->getNumArticle()]);
		$listArticleCommande->append($article);
	}

	//Recuperation du lieu choisi
	foreach($listLieu as $lieu){
		if($lieu->getNumeroLieu() == $_POST["Lieu"]){
			$lieuChoisi = $lieu;
			break;
		}
	}

	//set la commande
	$commande->setClient($_SESSION['login']);
	$commande->setDateCommande($dateCommande);
	$commande->setEstValide($_POST['submitCommande'] == "Valider");
	$commande->setFacture($facture);
	$commande->setLieuLivraison($lieuChoisi);
	$commande->setListArticle($listArticleCommande);


	$etat = $clientService->enregistrerCommande($commande);
	if($etat == null){
		//la commande est bien enregistre
		header('Location: ../web/commande_valide.php');
		exit();
	}
	//erreur enregistrement commande
	$_SESSION ['messageErreur'] = $etat;
	header('Location: ../action/clientNouvelleCommandeAction.php');
	exit();
}
